<template>
  <view>
    <!--  搜索组件  -->
    <search-components @onSearch="onChange"></search-components>
    <view
      class="flex justify-between items-center mt-6"
      v-if="searchHistory.length > 0"
    >
      <text>历史记录</text>
      <text class="mr-4 text-gray-400" @click="clearHistory">清除记录</text>
    </view>
    <view class="mt-6 ml-2 flex flex-wrap gap-3">
      <van-tag
        color="#ffe1e1"
        plain
        size="large"
        text-color="#ad0000"
        v-for="(item, index) in searchHistory"
        :key="index"
        style="margin-right: 18px"
      >
        <text @click="onChangeTo(item)">{{ item }}</text>
      </van-tag>
    </view>
  </view>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { uniq } from 'lodash'
import { useModal } from '@/common/utils/showModel'
import SearchComponents from '@/layout/components/SearchComponents.vue'

const { showModal } = useModal()
const searchHistory = ref<string[]>([])
const onChange = (value: string) => {
  searchHistory.value.unshift(value)
  searchHistory.value = uniq(searchHistory.value)
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop()
  }
  uni.setStorageSync('searchHistory', searchHistory.value)
  uni.navigateTo({
    url: `/pages/search-result/search-result?keyword=${value}`
  })
}
onMounted(() => {
  if (searchHistory.value.length > 0 || uni.getStorageSync('searchHistory')) {
    searchHistory.value = uni.getStorageSync('searchHistory')
  }
})
const clearHistory = () => {
  showModal('提示', '确定要清除历史记录吗？').then((res) => {
    if (res) {
      uni.removeStorageSync('searchHistory')
      searchHistory.value.length = 0
    }
  })
}
const onChangeTo = (value: string) => {
  console.log(value)
  uni.navigateTo({
    url: `/pages/search-result/search-result?keyword=${value}`
  })
}
</script>
<script lang="ts">
export default {
  name: 'SearchComponents'
}
</script>
<style scoped></style>
